package com.qingding.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.qingding.activity.NewRemind;
import com.qingding.R;
import com.qingding.activity.RemindDetail;
import com.qingding.model.Remind;
import org.litepal.LitePal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ShuRiFragment#newInstance} factory method to
 * create an instance of this fragment.
 */

//这个类其实也就是到我们进入程序之后可以看到主页面，但其实主页面显示的那个离目标还有多少天的Fragment
public class ShuRiFragment extends Fragment {
    private List<Remind> remindList = null;
    private List<Map<String, String>> list = null;
    private ListView listView;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public ShuRiFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShuRiFragment.
     */
    // TODO: Rename and change types and number of parameters
    //静态构造方法，并且传入一个Buddle对象
    public static ShuRiFragment newInstance(String param1, String param2) {
        ShuRiFragment fragment = new ShuRiFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    //跟JingXuanFragment相似
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }



    }

    //返回fragment_shu_ri.xml布局文件，
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView=inflater.inflate(R.layout.fragment_shu_ri, container, false);
        ImageButton addRemind=(ImageButton)myView.findViewById(R.id.add);
        listView = (ListView) myView.findViewById(R.id.listView);
        //从数据库获取数据
        getData();
        //设置ListView参数
        initListView();

        //并且将布局文件中的左上角的按钮实例化，为其添加时间监听器，使其跳转到NewRemind活动。
        addRemind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),NewRemind.class);
                startActivity(intent);
            }
        });

        //我们实现了View类的内部接口，并且实例化对象,使其跳转到RemindDetail.class这个活动
        View.OnClickListener listener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),RemindDetail.class);
                startActivity(intent);
            }
        };
        //将上面加载的myView中找到time_thing布局,分别为这两个布局添加事件监听器
        LinearLayout editRemind=(LinearLayout) myView.findViewById(R.id.time_thing);
        TextView countDown=(TextView)myView.findViewById(R.id.count_down_number) ;
        //当我点击那个具体天数和目标事件的时候它会自动跳转到详细的界面
        countDown.setOnClickListener(listener);
        editRemind.setOnClickListener(listener);

        //这个类似于数日中下面那个阶段性的小目标，类似于备注,设置其背景透明度
        /*ListView listView = (ListView)  myView.findViewById(R.id.fill_thing);
        listView.getBackground().setAlpha(100);*/
        //ArrayAdapter

        return myView;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    /**
     * 从数据库中查询Remind表所有数据
     */
    private void getData() {

        if (remindList == null){
            remindList = new ArrayList<Remind>();
        }
        remindList = LitePal.findAll(Remind.class);
    }

    /**
     * 设置测试数据
     */
    private void setTestData(){
        Remind remind = new Remind();
        remind.setTitle("哈哈");
        remind.setDateAndTime("麻晓东");
        remind.save();
    }

    /**
     * 清空数据库测试
     */
    private void clearData(){
        LitePal.deleteAll(Remind.class);
    }


    /**
     * 初始化ListView设置
     */
    public void initListView(){
        list = new ArrayList<Map<String, String>>();
        for (int i = 0;i<remindList.size();i++){
            Map<String,String> map = new HashMap<String,String>();
            map.put("title",remindList.get(i).getTitle());
            map.put("date",remindList.get(i).getDateAndTime());
            list.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(
                getActivity(),
                list,
                R.layout.listview_item,new String[]{"title","date"},
                new int[]{R.id.title,R.id.date});
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("确定删除？")
                        .setTitle("提示")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i1) {
                                Remind remind = remindList.get(i);
                                LitePal.delete(Remind.class,remind.getId());
                                remindList = LitePal.findAll(Remind.class);
                                initListView();
                            }
                        });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.create().show();
                return false;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //从数据库获取数据
        getData();
        initListView();
    }
}
